#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
int count = 0; // 全局变量,计时用
void *thread_fun1(void *arg)
{
  while (1)
  {
    count++;
    // sleep(1);
    pthread_testcancel(); // 设置取消点
  }
}

void *thread_fun2(void *arg)
{
  // 1-1000的累加
  int *sum;
  sum = (int *)malloc(sizeof(int));
  int i = 1;
  for (; i <= 1000; i++)
  {
    *sum += i;
  }
  pthread_exit((void *)sum);
}

int main()
{
  int *sum;
  pthread_t tid1, tid2; // 定义线程id
  int ret1 = pthread_create(&tid1, NULL, thread_fun1, NULL);
  if (ret1 != 0)
  {
    printf("thread create error:%s\n", strerror(ret1));
    exit(1);
  }
  int ret2 = pthread_create(&tid2, NULL, thread_fun2, NULL);
  if (ret2 != 0)
  {
    printf("thread create error:%s\n", strerror(ret1));
    exit(1);
  }

  // 等待线程二结束
  int ret3 = pthread_join(tid2, (void **)&sum);
  if (ret3 != 0)
  {
    printf("thread join error:%s\n", strerror(ret3));
    exit(1);
  }
  // 打印计算结果
  printf("sum = %d\n", *sum);

  // 取消线程1
  int ret4 = pthread_cancel(tid1);
  if (ret4 != 0)
  {
    printf("thread cancel error:%s\n", strerror(ret4));
    exit(1);
  }

  // 打印计数结果
  printf("count = %d\n", count);

  return 0;
}